__author__ = 'Daan'

import os

from unittests.stubs.common.verboseprint import printVerbose

class stub_os(object):
    def __init__(self, verbose=None):
        self.verbose = verbose or False


    def stub_open(self):

        def open(path, *args, **kwargs):
            printVerbose("os.open path=%s" % path, args, kwargs, self.verbose)

            return self.open(path, *args, **kwargs)

        os.open = open

    def stub_open_error(self, raiseOnMatch, exc_type, exc_msg):
        raiseOnMatch = raiseOnMatch or []

        def open(path, *args, **kwargs):
            printVerbose("os.open path=%s" % path, args, kwargs, self.verbose)

            if not raiseOnMatch or path in raiseOnMatch:
                raise exc_type(exc_msg)

            return self.open(path, *args, **kwargs)

        os.open = open

    def stub_listdir(self, retval=None):

        def listdir(*args, **kwargs):
            printVerbose("os.listdir args={0}, kwargs={1}", args, kwargs, self.verbose)

            return retval or []

        os.listdir = listdir

    def stub_listdir_raise(self, retval=None, raiseOnMatch=None, exc_type=None, exc_msg=None):

        raiseOnMatch = raiseOnMatch or []

        def listdir(path, *args, **kwargs):
            printVerbose("os.listdir path=%s args={0}, kwargs={1}" % path, args, kwargs, self.verbose)

            if not raiseOnMatch or path in raiseOnMatch:
                raise exc_type(exc_msg)

            return retval or []

        os.listdir = listdir

    def __enter__(self):
        self.open = os.open
        self.listdir = os.listdir

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.open != os.open:
            os.open = self.open

        if self.listdir != os.listdir:
            os.listdir = self.listdir
